import { getGlobalEnv } from "@/utils/constants";
import { isNavigationFailure, NavigationHookAfter, Router } from "vue-router";

const TITLE_SEPARATOR = " | ";

const { appTitle } = getGlobalEnv();

const titleHook: NavigationHookAfter = function (to, from, failure) {
  if (isNavigationFailure(failure)) return;

  if (to.meta.title) {
    document.title = [
      ...to.matched.map(({ meta }) => meta.title).reverse(),
      appTitle,
    ].join(TITLE_SEPARATOR);
  }
};

export default function createTitleHook(router: Router) {
  router.afterEach(titleHook);
}
